import EXIF from 'exif-js'
import "@/assets/js/common.js";
import "./index.css";
// import vgLogoImg from "@/assets/img/VG96.png";
// import cyberpunkImgZH from "@/assets/img/cyberpunk_zh.png";
import  fliterJson from "@/assets/config/fliterJson.js";
import VGKonva from "@/assets/js/VGKonva";
import { downCanvasImg,debounce,imgChangeToBase,rotateImg,isMobile ,dataURL2blob } from "@/assets/js/utility";
import pixelsJS  from "@/assets/pixels/lib/index.js";

$(function () {
  let VGKonvas = new VGKonva(); //实例化
  //修改图片引入从静态文件中防止出错
  let cyberpunkImgZH = $("#cyberpunkImgZH")[0].src;
  let cyberpunkImgEN = $("#cyberpunkImgEN")[0].src;
  let vgLogoImg = $("#vgLogoImg")[0].src;
  //判断是否是移动端
  if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) { //移动端
    //TODO
    $(".filterImg div button").css("display","block !important")
  }
  //禁止原生
  $(document).on({
    dragleave: function (e) {    //拖离 
      e.preventDefault();
    },
    drop: function (e) {  //拖后放 
      e.preventDefault();
    },
    dragenter: function (e) {    //拖进 
      e.preventDefault();
    },
    dragover: function (e) {    //拖来拖去 
      e.preventDefault();
    }
  });

  //剪切板
  document.addEventListener("paste", function (e) {
    var cbd = e.clipboardData;
    var ua = window.navigator.userAgent;
    // 如果是 Safari 直接 return
    if ( !(e.clipboardData && e.clipboardData.items) ) {
      return;
    }
    // Mac平台下Chrome49版本以下 复制Finder中的文件的Bug Hack掉
    if(cbd.items && cbd.items.length === 2 && cbd.items[0].kind === "string" && cbd.items[1].kind === "file" &&
        cbd.types && cbd.types.length === 2 && cbd.types[0] === "text/plain" && cbd.types[1] === "Files" &&
        ua.match(/Macintosh/i) && Number(ua.match(/Chrome\/(\d{2})/i)[1]) < 49){
      return;
    }
    for(var i = 0; i < cbd.items.length; i++) {
      var item = cbd.items[i];
      console.log(item)
      if(item.kind == "file"){
        
        var blob = item.getAsFile();
        if(!blob){
          alert("获取图片失败，如果是复制的qq请打开图片后复制")
          return;
        }
        if (blob.size === 0) {
          return;
        }
        // console.log(blob)
        if(!$("#drop_area").is(":hidden")){
          createImg(blob,true)
        } 
      
        // blob 就是从剪切板获得的文件 可以进行上传或其他操作
      }
    }
  }, false);

  var box = document.getElementById('drop_area'); //拖拽区域 
  box.addEventListener("dragenter", function () {
    $(box).addClass("active")
  })
  box.addEventListener("dragleave", function () {
    $(box).removeClass("active")
  })
  box.addEventListener("drop", function (e) {
    $(box).addClass("active")
    e.preventDefault(); //取消默认浏览器拖拽效果 
    var fileList = e.dataTransfer.files; //获取文件对象 
    createImg(fileList)
  }, false);




  // VGKonvas.drawCanvasBG()
  $("#checkLanguage").on("click", "input", function () {
    $("#checkLanguage input").prop("checked", false)
    $(this).prop("checked", true)
    let flg = $(this).val()
    if (VGKonvas.ischangeLanguage) {
      flg == "zh" ? VGKonvas.changeLanguageImage("cyberpunkImg", cyberpunkImgZH) : VGKonvas.changeLanguageImage("cyberpunkImg", cyberpunkImgEN)
    }
  })

  $("#drop_area").click(function () {
    return $("#uploadInput").click()
  })
  $("#uploadInput").on('change', function (e) {
    //e.currentTarget.files 是一个数组，如果支持多个文件，则需要遍历
    if ($(this)[0].files) {
      createImg($(this)[0].files)
    }
  });

  function createImg(files,isCV=false) {
    // isCV是不是粘贴复制
 
    if (files.length == 0) {
      return false;
    }
    let file
    isCV?file=files:file=files[0];

   
    
    //检测文件是不是图片 
    if (file.type.indexOf('image') === -1) {
      alert("您拖的不是图片！");
      return false;
    }
    var filesize = Math.floor((file.size) / 1024);
    console.log(filesize)
    if (filesize > (1024 * 10)&&!isCV) {
      alert("上传大小不能超过10M");
      return false;
    }
    if (filesize > (1024 * 10*10)&&isCV) {
      alert("上传大小不能超过10M");
      return false;
    }
    var img = window.URL.createObjectURL(file);
    var str = "<img src='" + img + "'>";
    
    $("#drop_area>*").hide()
    $("#drop_area").append(str).hide();

    if (isMobile()) { //移动端
      //TODO
      EXIF.getData(file, function(){
        if(!$.isEmptyObject(this.exifdata)){
          // 这里面可以看到值，想要什么直接获取即可。
          console.log('getAllTags', EXIF.getAllTags(this));
          let Orientation = EXIF.getTag(this, 'Orientation')
          if(Orientation&&Orientation != "" && Orientation != 1){
            // alert("需要旋转"+Orientation)
            let imgc  = new Image()
            imgc.src = img
            imgc.onload=()=>{
              switch(Orientation){
              case 6://需要顺时针90度旋转
                drawVGKonvas(rotateImg(imgc,90),true)
                break;
              case 8://需要逆时针90度旋转
                drawVGKonvas(rotateImg(imgc,270),true)
                break;
              case 3://需要180度旋转
                drawVGKonvas(rotateImg(imgc,180),true)
                break;
              }
              // drawVGKonvas(img)
              // drawVGKonvas(rotateImg(imgc,90))
            }
          }else{
            drawVGKonvas(img)
          }
        }else{
          drawVGKonvas(img)
        }
      });
    }else{
      drawVGKonvas(img)
    }



    // $("#next").off().click(function () {
    // console.log(VGKonvas.isNext)
    // if (VGKonvas.isNext) {

    // } else {
    //   alert("请先上传图片")

    // }
    // })

  }

  function drawVGKonvas(img,isR=false){
    if(isR){
      $("#drop_area img").attr("src",img)
    }
    VGKonvas.drawCanvasBG(img).then(res => {
      $("#drop_area").hide()
      $("#container").show()
      $(".operator-btn-box").show()
      VGKonvas.drawCanvas(vgLogoImg, '', "bottomRight",false,0.5,0.6).then(res => {
        if ($("#checkLanguage input:checked").val() == "zh") {
          VGKonvas.drawCanvas(cyberpunkImgZH, "cyberpunkImg", "bottomCenter")
        } else {
          VGKonvas.drawCanvas(cyberpunkImgEN, "cyberpunkImg", "bottomCenter")
        }
        //上一步
        $("#prev").off().on("click", function () {
          prevNextTogle()
        })
          
      })
      //绘制背景完成后 清空input的val
      $("#uploadInput")[0].value=""
    })
  }
  // $("#next").click(function(){
  //   alert("请先上传图片")
  // })

  //处理上一步下一步的显示
  function prevNextTogle(s="prev"){
    if(s=="prev"){
      VGKonvas.showTransformer()
      $("#drop_area").show().find("img").remove()
      $("#drop_area>*").show() //预览区域
      $("#container").hide()
      $(".operator-btn-box").hide()
      $(".filterImg").html("")
      $(".checkLanguage").show()
      $("#filter").prop("disabled",false)
      $("#moreFilter").hide()//更多滤镜
    }else{

    }
  }

  $(".save").click(function () {
    var id = $(this).attr("id");
    VGKonvas.toggleTransformer()
    var canvasimg = $("#container canvas")[0];
    id == "sava" ? downCanvasImg(canvasimg) : downCanvasImg(canvasimg);
    setTimeout(() => {
      VGKonvas.toggleTransformer()
    }, 300);
  })


  $(".operation-input input").on("input",
    debounce(function(){
      if($(this).parents(".operation-input").hasClass("RGB-input")){
        VGKonvas.filtersUpdata("RGB", {
          blue: $(".RGBblue").val(),
          red: $(".RGBred").val(),
          green: $(".RGBgreen").val(),
          alpha: $(".RGBalpha").val() * 0.1
        }
        )}
      if($(this).parents(".operation-input").hasClass("Mask-input")){
        VGKonvas.filtersUpdata("Mask", {
          threshold: $(".MaskThreshold").val()
        })
      }
      // console.log(1)
    },100,false)
    // console.log($(this).val())
  )


  // $("#filter").on("click", function () {
  //   $(".filterBox").addClass("active")
  // })
  // $(".filterBox .close > *").on("click",function(){
  //   $(".filterBox").removeClass("active")
  // })

  // $(".filterBox .operation").on("click","button",function(){
  //   let type =  $(this).attr("data-type")
  //   $(".operation-input").hide()
  //   $(`.${type}-input`).show()
  //   VGKonvas.filters(type)
  // })
  //滤镜  

  var fliterJsonData  = fliterJson
  fliterJsonData.unshift("原图")
  var pixelsFliterJSData  = pixelsJS.getFilterList()
  pixelsFliterJSData.unshift("")

  pixelsJS.getFilterList()
  $("#filter").on("click",function(){
    $(".filterImg").html("")
    $(".filterLayer").css("display","flex")

    $("#container").hide()
    $(this).prop("disabled",true)
    VGKonvas.removeBG()
    //VGKonvas.getBGData()
    $(".checkLanguage").hide()
    VGKonvas.toggleTransformer()
    let imgData =  $("#container canvas")[0].toDataURL("image/png")
    let imgSrc = $("#drop_area img").attr("src")
    let  width =  $("#container canvas").attr("width");
    let  height = $("#container canvas").attr("height");
    //修复在 滤镜使用大图/小图 渲染错误
    //  if($("#container>div").width()<$("#container canvas").attr("width")){
    //这里base64可用blon对象
    let ary =  pixelsFliterJSData;
    let aryT = fliterJsonData;
    imgChangeToBase({width:width,height:height,base64:imgSrc},function(data) {
      let len  =  24;
      if(isMobile()){
        len=12
   
      }
      $("#moreFilter").show()
      
      doFilterImg(data,imgData,0,len)

      $("#moreFilter").attr("data-start",len)
      $("#moreFilter span").text("更多")

      $("#moreFilter").off().on("click",function(){
        let s = Number($("#moreFilter").attr("data-start"))
        doFilterImg(data,imgData,s,s+len)
        console.log("xxxxxxxx",s)
        $("#moreFilter").attr("data-start",s+len)
      })
      return
      // doFilterImg(data,imgData)
    })
    //  }
    //  else{
    //    doFilterImg(imgData)
    //  }
    // doFilterImg(imgSrc,imgData)
 
   
    function doFilterImg(imgSrc,imgData,start=0,end=ary.length){
      //  let ary = ["","horizontal_lines","extreme_offset_blue","extreme_offset_green","offset_green","extra_offset_blue","extra_offset_red","extra_offset_green","extreme_offset_red","specks_redscale","haze"]
   
      if(end>=ary.length){
        end=ary.length
        $("#moreFilter span").text("没有更多了")
      }
      //ary.length=2
      for(let i= start;i<end;i++){
        $(".filterLayer").show()
        let str
        if(isMobile()){
          str = '<div><button type="button" class="z-button z-button--primary"><!----><!----><span>下载或长按保存</span></button><i>'+aryT[i]+'</i></div>';
        }else{
          str = '<div><button type="button" class="z-button z-button--primary"><!----><!----><span>下载或右键复制</span></button><i>'+aryT[i]+'</i></div>';
        }
       
        let strO = $(str)
        $(".filterImg").append(strO)
        console.log(ary[i])

        let imgObj = new Image();
        imgObj.src = imgSrc
        imgObj.onload=function(){
          strO.prepend(imgObj)
          pixelsJS.filterImg(  $(strO).find("img")[0],ary[i],{width:width,height:height}); 
          let canvas = strO.find("canvas")[0]
          let imgObjLogo = new Image();
          imgObjLogo.src = imgData
          imgObjLogo.onload=function(){
            let ctx = canvas.getContext('2d');
            ctx.drawImage(imgObjLogo,0,0,width,height)
            let imgdataPre =  canvas.toDataURL("image/png", 1)
            imgdataPre =    URL.createObjectURL(dataURL2blob(imgdataPre))
            // let imgStr =`<img src="${imgdataPre}">`
            if(isMobile()){ //如果是手机端就转换成imge
              let imgObjLogo2 = new Image();
              imgObjLogo2.src = imgdataPre
              imgObjLogo2.onload=function(){
                canvas.parentNode.replaceChild (imgObjLogo2,canvas ) 
                if(i = ary.length-1){
                  $(".filterLayer").hide()
                }
              }
            }else{
              if(i = ary.length-1){
                $(".filterLayer").hide()
              }
            }
          }
          // console.log(canvas)
        }
      }

    }
    // let img = new Image();
    // img.src = imgData

    // $("#createImg").attr("src",imgData) 
    // $("#createImg")[0].onload =function(){
    //   pixelsJS.filterImg( $("#createImg")[0], "radio"); 
    // }
    // pixelsJS.filterImg($("#cyberpunkImgEN")[0], "twenties"); 
    //  var newImgData =    pixelsJS.filterImgData(imgData, "twenties");
    //console.log(newImgData)
 
    // 坐标(0,0) 表示从此处开始绘制，相当于偏移。  

  })
  

  //图片下载
  $(".filterImg").on("click",'button',function(){
    let canvas1 = $(this).prev()[0];
    let text = $(this).next().text()
    text= text+'_'+Math.floor(Math.random()*10)+''+Math.floor(Math.random()*10)+''+Math.floor(Math.random()*10)+'_赛博朋克2077VG百科'
    // canvas1.tagName
    // debugger
    // alert(canvas1.tagName)
    if(canvas1.tagName=="IMG"){
      downCanvasImg($(canvas1).attr("src"),text)
    }else{
      downCanvasImg(canvas1.toDataURL("image/png"),text)
    }
  })

})
